package com.lsk.util;

import com.jfinal.weixin.sdk.kit.PaymentKit;
import com.jfinal.weixin.sdk.utils.HttpUtils;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;
import java.util.*;

public class WxpayReturn {


    public static final Logger log = (Logger) LoggerFactory.getLogger(WxpayReturn.class);
    public static final String REFUND_PAY = "https://api.mch.weixin.qq.com/secapi/pay/refund";
    public static final String ALGORITHM = "AES";
    public static final String ALGORITHM_MODE_PADDING = "AES/ECB/PKCS7Padding";



    public static SecretKeySpec key = new SecretKeySpec(MD5Util.MD5Encode("de28ffc5b3e04fc1bd72b0d3b9c0c40a", "UTF-8").toLowerCase().getBytes(), ALGORITHM);
    public String str;
    static String time;

    //退款需要的参数 用户的openid 订单总金额 退款金额  退款原因




    public static String encryptData(String data) throws Exception {
        Security.addProvider(new BouncyCastleProvider());


        // 创建密码器
        Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING, "BC");
        // 初始化
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return Base64Util.encode(cipher.doFinal(data.getBytes()));
    }

    public static String decryptData(String base64Data) throws Exception {
        Security.addProvider(new BouncyCastleProvider());
        Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING, "BC");
        cipher.init(Cipher.DECRYPT_MODE, key);
        return new String(cipher.doFinal(Base64Util.decode(base64Data)));
    }



    /**
     * 申请退款，内部添加了随机字符串nonce_str和签名sign
     * @param params 参数map，内部添加了随机字符串nonce_str和签名sign
     * @param paternerKey 商户密钥
     * @param certPath 证书文件目录
     * @return  map
     */
    public static Map<String, String> refunds(Map<String, String> params, String paternerKey, String certPath) {
        params.put("nonce_str", System.currentTimeMillis() + "");
        String sign = PaymentKit.createSign(params, paternerKey);
        params.put("sign", sign);
        String partner = params.get("mch_id");
        String xmlStr = HttpUtils.postSSL(REFUND_PAY, PaymentKit.toXml(params), certPath, partner);

        Map<String, String> map = new HashMap<String, String>();
        Document result = null;
        try {
            result = (Document) DocumentHelper.parseText(xmlStr);
            Element rootElt = (Element) result.getRootElement(); // 获取根节点
            List<Element> list = rootElt.elements();//获取根节点下所有节点
            for (Element element : list) {  //遍历节点
                map.put(element.getName(), element.getText()); //节点的name为map的key，text为map的value
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }


    //生成随机字符串
    public static String getRandomStringByLength(int length) {
        String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }
    public String time(){
        Long s= new Date().getTime();
        Random random=new Random();
        int result=random.nextInt(10);
        return s.toString();
    }

}
